package com.whales.lms.rms.scheduler;

import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.whales.lms.rms.scheduler.model.SchedulerLogVO;


/**
 * Task가 수행을 위한 Template method pattern이 적용된 Template Class
 */
public abstract class TaskTemplate implements Task {
	static Logger log = Logger.getLogger(TaskTemplate.class);
    private String conExpression;
    private long delay = 0;
    private long endTime = 0;
    private long startTime = 0;
    
    /**
     * 경과시간
     * @param start
     * @param end
     * @return
     */
    private double currentTime(long start, long end){
        return (end - start) / 1000.0;
    }
    
    /**
     * cronExpression 설정
     * @param conExpression	
     */
    public void setConExpression(String conExpression) {
        this.conExpression = conExpression;
    }
    
    /**
     * delay(반복 주기) 설정
     * @param delay	
     */
    public void setDelay(long delay) {
        this.delay = delay;
    }
    /**
     * 접속 종료 시간
     * @return
     */
    private long endTime(){
        this.endTime = System.currentTimeMillis();
        return this.endTime;
    }
    
    /**
     * cronExpression 설정 반환
     * @see eng.mdw.scheduling.Task#getConExpression()
     * @return
     */
    public String getConExpression() {
        return conExpression;
    }
    
    /**
     * delay 설정 반환
     * @see eng.mdw.scheduling.Task#getDelay()
     * @return
     */
    public long getDelay() {
        return delay;
    }
    
    /**
     * Scheduler Thread에서 호출되게 될 Template method 
     * @see java.lang.Runnable#run()
     */
    public void run(){
        SchedulerLogVO schedulerLogVO = new SchedulerLogVO();
        schedulerLogVO.setTaskName(this.getClass().getName());
        schedulerLogVO.setStartTime(new Timestamp(this.startTime()));        
        try{
            this.execute();
            schedulerLogVO.setSuccess("OK");
        }catch(Exception e){
            schedulerLogVO.setSuccess("FAIL");
            schedulerLogVO.setErrorMessage(e.getMessage());
        }
        schedulerLogVO.setEndTime(new Timestamp(this.endTime()));
        schedulerLogVO.setCurrentTime(this.currentTime(this.startTime, this.endTime));
        try {
        	log.trace(schedulerLogVO.getTaskName() + " result : " + schedulerLogVO.getSuccess());
//            schedulerLogService.create(schedulerLogVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * run method에서 호출될 task 구체클랫스를 구현하셔야 합니다. 
     * @see eng.mdw.scheduling.Task#execute()
     * @throws Exception
     */
    abstract public void execute() throws Exception;
    
    /**
     * 접속 시작 시간
     * @return
     */
    private long startTime(){
        this.startTime = System.currentTimeMillis();
        return this.startTime;
    }
}
